/**
 * 
 */
package edu.umd.clip.lm.model;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import edu.umd.clip.lm.util.*;
import edu.umd.clip.lm.factors.*;

/**
 * @author Denis Filimonov <den@cs.umd.edu>
 *
 */
public class WordTreePayload extends XMLizable {
	public static final String XML_ELEMENT_NAME = "word-tree-node";
	public static final String XML_WORD_NAME = "word";
	public final BinaryPrefix prefix;
	public final String word;
	public final int value;
	
	public WordTreePayload(BinaryPrefix p) {
		this(p, null);
	}
	
	public WordTreePayload(BinaryPrefix p, String t) {
		prefix = p;
		word = t;
		FactorTupleDescription desc = Experiment.getInstance().getTupleDescription();
		value = desc.getDictionary(desc.getMainFactorIndex()).getId(word);
	}

	public WordTreePayload(BinaryPrefix p, int value) {
		prefix = p;
		this.value = value; 
		FactorTupleDescription desc = Experiment.getInstance().getTupleDescription();
		word = desc.getDictionary(desc.getMainFactorIndex()).getWord(value);
	}
	
	public WordTreePayload(Element xmlnode) {
		assert(xmlnode.getTagName().equals(XML_ELEMENT_NAME));
		Element prefixElement = (Element) xmlnode.getElementsByTagName(BinaryPrefix.XML_ELEMENT_NAME).item(0);
		this.prefix = new BinaryPrefix(prefixElement);
		Element wordElement = XMLUtils.getFirstElementByTagName(xmlnode, XML_WORD_NAME);
		if (wordElement != null) {
			this.word = wordElement.getTextContent();
		} else {
			this.word = Dictionary.getNullWord();
		}
		FactorTupleDescription desc = Experiment.getInstance().getTupleDescription();
		value = desc.getDictionary(desc.getMainFactorIndex()).getId(word);
	}
	/* (non-Javadoc)
	 * @see edu.umd.clip.lm.util.XMLizable#createXML(org.w3c.dom.Document)
	 */
	@Override
	public Element createXML(Document doc) {
		Element element = doc.createElement(XML_ELEMENT_NAME);
		element.appendChild(prefix.createXML(doc));
		if (element != null) {
			Element wordElement = doc.createElement(XML_WORD_NAME);
			wordElement.setTextContent(word);
			element.appendChild(wordElement);
		}
		return element;
	}

	/* (non-Javadoc)
	 * @see edu.umd.clip.lm.util.XMLizable#getElementName()
	 */
	@Override
	public String getElementName() {
		return XML_ELEMENT_NAME;
	}
}
